import os
import requests
# 0 */20 * * * * jd_tz.py 监控通知
# const $ = new Env('监控通知')
# 设置企业微信应用的相关信息
corp_id = "ww54db7dd5adc72e8b"
app_secret = "etRufrFi__-MLIMcv7rlBZgpB173O5njRh5PM2rt9Zk"
app_agent_id = "1000005"
user_id = "YongLanPing"

log_directory = "/ql/data/log/guoluren1_glr_jd_luckdraw"
output_file = "/ql/data/scripts/luck_no.txt"
keyword = "提交地址成功"
num_logs_to_process = 10

# 获取指定目录下最新的num_logs_to_process个日志文件
log_files = sorted(os.listdir(log_directory), reverse=True)[:num_logs_to_process]

# 读取已经记录的行内容
existing_lines = set()
if os.path.exists(output_file):
    with open(output_file, "r") as f:
        existing_lines = set(f.read().splitlines())

# 遍历日志文件并查找关键词行
found_lines = []
for file in log_files:
    file_path = os.path.join(log_directory, file)
    with open(file_path, "r") as f:
        for line in f:
            if keyword in line and line not in existing_lines:
                found_lines.append(line.strip())

# 将找到的行写入输出文件
if found_lines:
    with open(output_file, "a") as f:
        f.write("\n".join(found_lines) + "\n")
    print("已将找到的行写入", output_file)

    # 准备推送的内容
    message = "\n".join(found_lines)  # 将找到的行内容拼接为一个字符串

    # 获取 access_token
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={app_secret}"
    response = requests.get(url)
    access_token = response.json().get("access_token")

    # 发送消息到企业微信应用
    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
    data = {
        "touser": user_id,
        "agentid": app_agent_id,
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    response = requests.post(url, json=data)
    if response.json().get("errcode") == 0:
        print("推送消息成功")
    else:
        print("推送消息失败")
else:
    print("未找到包含关键词的行")
